<template>
  <div id="container"></div>
</template>

<script setup>
import { gps_key } from '@/constant/gps/index.js'
import { onMounted, defineProps, watch, watchEffect, ref, nextTick } from 'vue';

let mapInitialized = false;
const loadMapAPI = () => {
  const script = document.createElement('script');
  script.src = `https://webapi.amap.com/maps?v=2.0&key=${gps_key}`;
  script.onload = () => {
    mapInitialized = true
    initMap();
  };
  document.head.appendChild(script);
}

const initMap = () => {
  if (longitude.value && latitude.value) {
    var map = new AMap.Map('container', {
      center: [longitude.value, latitude.value],
      layers: [new AMap.TileLayer.Satellite()],
      zoom: zoom.value,
      // layers: [],
    });
  }
  else {
    document.getElementById('container').innerHTML = "无坐标信息"
  }
}

let props = defineProps({
  latitude: {
    type: Number,
    default: null
  },
  longitude: {
    type: Number,
    default: null
  },
  zoom: {
    type: Number,
    default: 17
  }
})

let latitude = ref(props.latitude)
let longitude = ref(props.longitude)
let zoom = ref(props.zoom)

watchEffect(() => {
  latitude.value = props.latitude
  longitude.value = props.longitude
  zoom.value = props.zoom
  nextTick(() => {
    if (mapInitialized) {
      initMap();
    } else {
      loadMapAPI();
      initMap();
    }
  })
})


onMounted(() => {

})
</script>

<style lang="scss" scoped>
#container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 30px;
  color: rgb(158, 154, 154);
  box-sizing: border-box;
  border: 0.5px solid rgb(226, 218, 218);
}
</style>